#ifndef __COM_HPP__
#define __COM_HPP__


#include<iostream>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<cstring>
#include<cerrno>
#include<sys/types.h>
#include<cassert>
#include<string>

using namespace std;
#define PATHNAME "."
#define PROJID 0x6666
const size_t gsize=1024;
key_t GetKey()
{
    key_t k=ftok(PATHNAME,PROJID);
    if(k==-1)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(1);
    }
    return k;
}

string toHex(int x)
{
    char buffer[4];
    snprintf(buffer,sizeof buffer,"0x%x",x);
    return buffer;
}

int CreateShmHelp(key_t key,size_t size,int flag)
{
    int shmid=shmget(key,size,flag);
    if(shmid==-1)
    {
        cout<<"error" <<errno<<":"<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key,size_t size)
{
    CreateShmHelp(key,size,IPC_CREAT|IPC_EXCL);
}

int GetShm(key_t key,size_t size)
{
    CreateShmHelp(key,size,IPC_CREAT);
}

void DelShm(int shmid)
{
    int n=shmctl(shmid,IPC_RMID,nullptr);
    assert(n==-1);
    (void)n;
}
char*AttachShm(int shmid)
{
    char *p=(char*)shmat(shmid,nullptr,0);
    return p;

}
void DetachShm(char*p)
{
    int n=shmdt(p);
    assert(n!=-1);
    (void)n;
}


#endif
